package com.centanet.framework.network;

import android.support.v4.util.ArrayMap;

import com.centanet.framework.interfaces.IParamsEncode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * ArrayMap格式 参数格式化
 */
public class ArrayMapEncode implements IParamsEncode {

    private final ArrayMap<String, Object> arrayMap;

    public ArrayMapEncode(ArrayMap<String, Object> arrayMap) {
        this.arrayMap = arrayMap;
    }

    @Override
    public byte[] encode(String paramsEncoding) {
        StringBuilder encodedParams = new StringBuilder();
        try {
            if (arrayMap.isEmpty()) {
                return null;
            } else {
                for (Map.Entry<String, Object> entry : arrayMap.entrySet()) {
                    encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                    encodedParams.append('=');
                    encodedParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), paramsEncoding));
                    encodedParams.append('&');
                }
                return encodedParams.toString().getBytes(paramsEncoding);
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Encoding not supported: " + paramsEncoding, e);
        }
    }
}
